package com.xjm.api.admin;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjm.entity.model.ProductsModel;
import com.xjm.entity.model.ThemeProductsModel;
import com.xjm.entity.model.ThemesModel;
import com.xjm.entity.model.ThemesModel;
import com.xjm.entity.vo.PageVo;
import com.xjm.entity.vo.Result;
import com.xjm.service.IProductsService;
import com.xjm.service.IThemeProductsService;
import com.xjm.service.IThemesService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collector;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xjm
 * @since 2025-02-28
 */
@RestController
@RequestMapping("/admin/theme")
@RequiredArgsConstructor
public class ThemesController {
    private final IThemesService themesService;
    private final IProductsService productsService;
    private final IThemeProductsService themeProductsService;

    @GetMapping
    public Result<PageVo<ThemesModel>> list(
            @RequestParam(defaultValue = "1") Long page,
            @RequestParam(defaultValue = "5") Long size
    ) {
        return Result.success(themesService.page(new Page<>(page, size)));
    }

    @GetMapping("/{id}")
    public Result<ThemesModel> getById(@PathVariable Long id) {
        ThemesModel themesModel = themesService.getById(id);
        if (themesModel != null) {
            List<ThemeProductsModel> themeProducts = themeProductsService
                    .list(new LambdaQueryWrapper<ThemeProductsModel>()
                            .eq(ThemeProductsModel::getThemeId, id));
            List<Integer> productIds = themeProducts.stream().map(ThemeProductsModel::getProductId).toList();
            themesModel.setProductsModels(productsService.listByIds(productIds));
            themesModel.setProductIds(productIds);
        }
        return Result.success(themesModel);
    }

    @GetMapping("/products")
    public Result<List<ProductsModel>> getProducts(@RequestParam(required = false) String name) {
        LambdaQueryWrapper<ProductsModel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductsModel::getStatus, 1);
        wrapper.select(ProductsModel::getId, ProductsModel::getName);
        wrapper.orderByDesc(ProductsModel::getSales);
        wrapper.like(StrUtil.isNotBlank(name), ProductsModel::getName, name);
        wrapper.last("limit 5");
        return Result.success(productsService.list(wrapper));
    }

    @PostMapping
    public Result<ThemesModel> add(@RequestBody ThemesModel themesModel) {
        List<Integer> productIds = themesModel.getProductIds();
        if (productIds == null || productIds.isEmpty()) return Result.error("请选择商品");
        themesService.save(themesModel);
        List<ThemeProductsModel> list = new ArrayList<>();
        for (Integer productId : productIds) {
            ThemeProductsModel themeProductsModel = new ThemeProductsModel();
            themeProductsModel.setThemeId(themesModel.getId());
            themeProductsModel.setProductId(productId);
            list.add(themeProductsModel);
        }
        themeProductsService.saveBatch(list);
        return Result.success();
    }

    @PutMapping
    public Result<ThemesModel> update(@RequestBody ThemesModel themesModel) {
        List<Integer> productIds = themesModel.getProductIds();
        if (productIds == null || productIds.isEmpty()) return Result.error("请选择商品");
        // 先删除
        themeProductsService.remove(new LambdaQueryWrapper<ThemeProductsModel>().eq(ThemeProductsModel::getThemeId, themesModel.getId()));
        // 在批量插入
        List<ThemeProductsModel> list = new ArrayList<>();
        for (Integer productId : productIds) {
            ThemeProductsModel themeProductsModel = new ThemeProductsModel();
            themeProductsModel.setThemeId(themesModel.getId());
            themeProductsModel.setProductId(productId);
            list.add(themeProductsModel);
        }
        themeProductsService.saveBatch(list);
        themesModel.setUpdatedTime(null);
        themesService.updateById(themesModel);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<ThemesModel> delete(@PathVariable Long id) {
        themesService.removeById(id);
        return Result.success();
    }
}
